package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIDWorker;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    RedisIDWorker redisIDWorker;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Resource
    RedissonClient redissonClient;


    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    private static final String MQ_STREAM_KEY = "stream:orders";

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    //定义阻塞队列

    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    @PostConstruct
    private void init() {
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

    private class VoucherOrderHandler implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    //获取消息队列中的消息 XREADGROUP g1 c1 COUNT 1 BLOCK 2000  STREAM streams:order >
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(MQ_STREAM_KEY, ReadOffset.lastConsumed())
                    );

                    if(list==null || list.isEmpty()){
                        //获取失败：阻塞等待
                        continue;
                    }

                    //获取成功：创建订单
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> orderMap = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(orderMap, new VoucherOrder(), true);
                    handleVoucherOrder(voucherOrder);
                    //ACK确认
                    stringRedisTemplate.opsForStream().acknowledge(MQ_STREAM_KEY,"g1", record.getId());

                } catch (Exception e) {
                    log.info("处理订单异常，", e);
                    handlePendingList();
                }
            }
        }
    }

    private void handlePendingList() {
        while (true) {
            try {
                //获取消息队列中的消息 XREADGROUP g1 c1 COUNT 1 STREAM streams:order 0
                List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                        Consumer.from("g1", "c1"),
                        StreamReadOptions.empty().count(1),
                        StreamOffset.create(MQ_STREAM_KEY, ReadOffset.from("0"))
                );

                if(list==null || list.isEmpty()){
                    //pending处理完成
                    break;
                }

                //获取成功：创建订单
                MapRecord<String, Object, Object> record = list.get(0);
                Map<Object, Object> orderMap = record.getValue();
                VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(orderMap, new VoucherOrder(), true);
                handleVoucherOrder(voucherOrder);
                //ACK确认
                stringRedisTemplate.opsForStream().acknowledge(MQ_STREAM_KEY,"g1", record.getId());

            } catch (Exception e) {
                log.info("pending-list处理异常，", e);
            }
        }

    }

    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        Long userId = voucherOrder.getUserId();
        //加个锁，保险一点
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        //获取锁
        boolean isLock = lock.tryLock();
        if (!isLock) {
            log.info("请勿重复下单");
            return;
        }

        try {
            proxy.createVoucherOrder(voucherOrder);
        } finally {
            lock.unlock();
        }

    }

    IVoucherOrderService proxy;

    @Override
    public Result seckillVoucher(Long voucherId) throws InterruptedException {
        Long userId = UserHolder.getUser().getId();
        long orderId = redisIDWorker.createId("order");

        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString(), String.valueOf(orderId)
        );

        int res = result.intValue();
        if (res != 0) {
            return Result.fail(res == 1 ? "库存不足" : "请勿重复下单");
        }

        //设置动态代理
        proxy = (IVoucherOrderService) AopContext.currentProxy();

        return Result.ok(orderId);
    }

  /*  private static final BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);

    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        Long userId = voucherOrder.getUserId();
        //加个锁，保险一点
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        //获取锁
        boolean isLock = lock.tryLock();
        if (!isLock) {
            log.info("请勿重复下单");
            return;
        }

        try {
            proxy.createVoucherOrder(voucherOrder);
        } finally {
            lock.unlock();
        }

    }
*/

/*
    @Override
    public Result seckillVoucher(Long voucherId) throws InterruptedException {
        Long userId = UserHolder.getUser().getId();

        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString()
        );

        int res = result.intValue();
        if (res != 0) {
            return Result.fail(res == 1 ? "库存不足" : "请勿重复下单");
        }

        //使用阻塞队列将订单存储到数据库中
        long orderId = redisIDWorker.createId("order");
        Long userID = UserHolder.getUser().getId();
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setVoucherId(voucherId);
        voucherOrder.setUserId(userID);
        voucherOrder.setId(orderId);

        //设置动态代理
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        //将订单消息放入阻塞队列中
        orderTasks.add(voucherOrder);

        return Result.ok(orderId);
    }
*/

    /* @Override
        public Result seckillVoucher(Long voucherId) throws InterruptedException {
            SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
            //活动时间检查
            if (LocalDateTime.now().isBefore(seckillVoucher.getBeginTime())) {
                return Result.fail("活动尚未开始");
            }

            if (LocalDateTime.now().isAfter(seckillVoucher.getEndTime())) {
                return Result.fail("活动已经结束");
            }

            //库存检查
            if (seckillVoucher.getStock() < 1) {
                return Result.fail("库存不足");
            }

            Long userID = UserHolder.getUser().getId();
            //添加悲观锁，无法避免集群环境下的多进程并发问题
    //        synchronized (userID.toString().intern()){
    //            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
    //            return proxy.createVoucherOrder(voucherId);
    //        }

            //使用分布式锁
            //RedisLockImpl redisLock = new RedisLockImpl(stringRedisTemplate,"order:"+userID);
            RLock redisLock = redissonClient.getLock("lock:order:" + userID);

            if(!redisLock.tryLock(1,10, TimeUnit.SECONDS)){
                return Result.fail("请勿重复下单");
            }

            try{
                IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
                return proxy.createVoucherOrder(voucherId);
            }finally {
                redisLock.unlock();
            }
        }
    */
    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        //用户ID
        Long userID = voucherOrder.getUserId();

        Integer count = query().eq("user_id", userID).eq("voucher_id", voucherOrder.getVoucherId()).count();
        if (count > 0) {
            log.info("请勿重复下单");
            return;
        }

        boolean success = seckillVoucherService
                .update()
                .setSql("stock = stock-1")
                .eq("voucher_id", voucherOrder.getVoucherId())
                .gt("stock", 0)
                .update();
        if (!success) {
            log.error("库存不足");
            return;
        }

        //将记录写入数据库
        save(voucherOrder);
    }
}
